<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 新增</a-button>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" @success="reload" />
      </template>
    </BasicTable>

    <AddBookModal :data="row" @register="registerAddBookModal" @success="onSuccess" />
  </div>
</template>

<script lang="ts" name="book-mange" setup>
  import { ref } from 'vue';
  import { BasicTable, TableAction, ActionItem } from '/@/components/Table';
  import AddBookModal from './components/AddBookModal.vue';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { columns, searchFormSchema } from './data';
  import { listNoCareTenant, deleteBook } from './api';

  const { createMessage } = useMessage();

  //密码model
  const [registerAddBookModal, { openModal: openAddBookModal, setModalProps }] = useModal();

  // 列表页面公共参数、方法
  const { tableContext } = useListPage({
    designScope: 'book-list',
    tableProps: {
      title: '图书列表',
      api: listNoCareTenant,
      columns: columns,
      size: 'small',
      formConfig: {
        schemas: searchFormSchema,
      },
      actionColumn: {
        width: 120,
      },
      fetchSetting: {
        listField: 'result.items',
        totalField: 'result.total',
      },
    },
  });

  //注册table数据
  const [registerTable, { reload }] = tableContext;

  const row = ref({});

  /**
   * 新增事件
   */
  function handleCreate() {
    openAddBookModal(true);
    setModalProps({ title: '新增' });
    row.value = {};
  }
  /**
   * 编辑事件
   */
  async function handleEdit(data: Recordable) {
    openAddBookModal(true);
    setModalProps({ title: '编辑' });
    row.value = data;
  }

  function onSuccess() {
    row.value = {};
    reload();
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteBook({ bookId: record.bookId }, reload);
    createMessage.success('删除成功');
  }

  /**
   * 操作栏
   */
  function getTableAction(record): ActionItem[] {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
        },
      },
    ];
  }
</script>

<style scoped></style>
